package com.bookcity.enums;

import com.bookcity.utils.UtilEnum;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * CodeEnumHandler
 *
 * @Author : lostprobe
 * @Date : 2022/5/11 16:17
 * @Brief : CodeEnumHandler
 */
@NoArgsConstructor
@AllArgsConstructor
public class CodeEnumHandler<E extends Enum<E> & BaseEnum> extends BaseTypeHandler<BaseEnum> {

    private Class<E> type;
    
    public E getEnums(int code) {
        try {
            return UtilEnum.getEnum(type, code);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("code:" + code + " is not a valid code");
        }
    }

    @Override
    public E getNullableResult(ResultSet arg0, String arg1) throws SQLException {
        int code = arg0.getInt(arg1);
        return arg0.wasNull() ? null : getEnums(code);
    }

    @Override
    public E getNullableResult(ResultSet arg0, int arg1) throws SQLException {
        int code = arg0.getInt(arg1);
        return arg0.wasNull() ? null : getEnums(code);
    }

    @Override
    public E getNullableResult(CallableStatement arg0, int arg1) throws SQLException {
        int code = arg0.getInt(arg1);
        return arg0.wasNull() ? null : getEnums(code);
    }

    @Override
    public void setNonNullParameter(PreparedStatement arg0, int arg1, BaseEnum arg2, JdbcType arg3)
            throws SQLException {
        arg0.setInt(arg1, arg2.getCode());
    }
    
}
